package com.jiedeng.controller.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jiedeng.controller.Rst;
import com.jiedeng.model.Corp;
import com.jiedeng.model.EpsTree;
import com.jiedeng.model.Person;
import com.jiedeng.util.ForwardConstants;
import com.jiedeng.util.SessionUtil;
import com.jiedeng.util.httpclient.HttpClientHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录首页
 *
 * @author zhouyb
 */
@Controller
@Scope("prototype")
@RequestMapping("/")
public class InitController {
    private final Logger logger = LoggerFactory.getLogger(InitController.class);
    @Value("${config.http.client.url}")
    public String url;

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping(value = "")
    public String toIndex() {
        return ForwardConstants.REDIRECT + ForwardConstants.LOGIN;
    }

    /**
     * 用户登陆
     *
     * @return
     */
    @RequestMapping(value = "/user-login", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
    public String login(HttpServletRequest request, Model model, String username, String password, String veryCode) {
        try {
            String validateC = (String) request.getSession().getAttribute("validateCode");
            model.addAttribute("ctx", request.getContextPath());
            if (StringUtils.isEmpty(validateC) || !validateC.equals(veryCode.toLowerCase())) {
                model.addAttribute("error", "validation code input error");
                //model.addAttribute("error", "验证码输入错误");
                return "login";
            }
            Map map = new HashMap<>();
            map.put("loginid", username);
            map.put("password", password);
            //这里就是请求后台api
            //ret就是返回的结果，然后根据结果去判断怎么提示或者跳转
            String ret = HttpClientHelper.postRequest2(url + "/admin/signin", map, "utf-8", "");
            JSONObject json = JSONObject.parseObject(ret.trim());
            String code = json.get("code").toString();
            String message = json.get("message").toString();
            if ("1".equals(code)) {
                Person userInfo = JSON.parseObject(json.get("userInfo").toString(), new TypeReference<Person>() {
                });
                //request.getSession().setAttribute("userInfo",userInfo);
                SessionUtil.setUserSession(userInfo);
                SessionUtil.setUserIdSession(userInfo.getId() + "");
                SessionUtil.setUserNameSession(userInfo.getName());
                //单位
                String ret2 = HttpClientHelper.doGet(url + "/homepage/getCorpById?id=" + userInfo.getCorpId());
                Corp corp = JSON.parseObject(ret2.trim(), new TypeReference<Corp>() {
                });
                SessionUtil.setUserCorpNameSession(corp.getCaption());
                return ForwardConstants.REDIRECT + ForwardConstants.INDEX;
            } else {
                String mess = message.replaceAll("\"", "");
                //switch (code) {
                //    case "2":
                //        mess = "用户名或密码错误";
                //        break;
                //    case "3":
                //        mess = "用户被锁定，请联系管理员！";
                //        break;
                //    case "4":
                //        mess = "在登录时间之外";
                //        break;
                //    default:
                //        mess = "出错了";
                //}
                //request.setAttribute(ForwardConstants.ERROR, message);
                model.addAttribute("error", mess);
            }
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "出错了");
            return "login";
        }
    }

    /**
     * 进入登陆画面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/login-page", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String loginUI(HttpServletRequest request, Model model) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("error", "");
        return "login";
    }

    /**
     * 进入主页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String indexUI(HttpServletRequest request, Model model) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            Map map = new HashMap<>();
            //首页左边菜单
            String ret = HttpClientHelper.postRequest2(url + "/multi/eps/all", map, "utf-8", "");
            List<EpsTree> menus = JSON.parseObject(ret.trim(), new TypeReference<List<EpsTree>>() {
            });
            model.addAttribute("treeMenu", menus);
            //用户
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";
    }

    /**
     * 密码重置
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/passwordReset", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String passwordResetUI(HttpServletRequest request, Model model) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("errorReset", "");
        return "passwordReset";
    }

    /**
     * 获取验证码
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("/getVeryCode")
    public String getVeryCode(String phone, HttpServletRequest request) {
        try {
            if (!StringUtils.isEmpty(phone)) {
                HttpSession session = request.getSession();
                Map map = new HashMap<>();
                map.put("phone", phone);
                String ret = HttpClientHelper.postRequest2(url + "/common/getVeryCode", map, "utf-8", "");
                Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
                });
                int code = rst.getResultCode();
                if (code == 0) {
                    session.setAttribute("phoneCode", rst.getMsg());
                    session.setAttribute("phoneNum", phone);
                    return ForwardConstants.SUCCESS;
                } else {
                    return rst.getMsg();
                }
            } else {
                return "手机号码不能为空";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }

    /**
     * 验证手机验证码
     *
     * @param code    验证码
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkPhoneCode")
    public String checkPhoneCode(String code, HttpServletRequest request) {
        //获取session验证码
        String phoneCode = (String) request.getSession().getAttribute("phoneCode");
        if (!StringUtils.isEmpty(code) && !StringUtils.isEmpty(phoneCode) && phoneCode.equals(code)) {
            request.getSession().removeAttribute("phoneCode");
            return ForwardConstants.SUCCESS;
        }
        return ForwardConstants.ERROR;
    }

    /**
     * 修改密码
     *
     * @param password
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/user-resetPwd")
    public String resetPwd(String password, HttpServletRequest request, Model model) {
        model.addAttribute("ctx", request.getContextPath());
        String phoneNum = (String) request.getSession().getAttribute("phoneNum");
        request.getSession().removeAttribute("phoneNum");
        if (StringUtils.isEmpty(phoneNum)) {
            model.addAttribute("errorReset", "修改失败，请重新验证");
            return ForwardConstants.REDIRECT + "passwordReset";
        }
        Map map = new HashMap<>();
        map.put("phoneNum", phoneNum);
        map.put("password", password);
        String ret = null;
        try {
            ret = HttpClientHelper.postRequest2(url + "/init/resetPassword", map, "utf-8", "");
            Rst rst = JSON.parseObject(ret.trim(), new TypeReference<Rst>() {
            });
            if (rst.getResultCode() == 0) {
                model.addAttribute("error", "");
                return ForwardConstants.REDIRECT + ForwardConstants.LOGIN;
            } else {
                model.addAttribute("errorReset", rst.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errorReset", "出错了");
            logger.error("修改密码出错", e);
        }

        return ForwardConstants.REDIRECT + "passwordReset";
    }

    /**
     * 退出系统
     *
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        // 使用权限管理工具进行用户的退出，注销登录
        SessionUtil.removeUserSession();
        SessionUtil.removeUserIdSession();
        //SessionUtil.removeAccessTokenSession();
        return ForwardConstants.REDIRECT + ForwardConstants.LOGIN;
    }
    /**
     * 没权限跳转空白页面
     *
     * @return
     */
    @RequestMapping("jurisdictionBlank")
    public String jurisdictionBlank(HttpServletRequest request, Model model) {
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("error", "");
        return "jurisdiction";
    }

    @ResponseBody
    @RequestMapping("modules/{module}/{module2}/{url}")
    public String module2(@PathVariable("module") String module, @PathVariable("module2") String module2, @PathVariable("url") String url2, @RequestParam Map<String, Object> params) {
        try {
            String clientUrl = url + "/" + module + "/" + module2 + "/" + url2;
            //ProType proType= Class.forName("com.jiedeng.model.ProType").getInterfaces();
            if (!StringUtils.isEmpty(params)) {
                clientUrl += "?";
                clientUrl += getParam(params);

            }
            String ret = HttpClientHelper.doGet(clientUrl);
            return ret;
            ///原返回
           /* List<Map<String, Object>> classList = new ArrayList<Map<String, Object>>();
            if (ret != null) {
                classList = JSON.parseObject(ret.trim(), new TypeReference<List<Map<String, Object>>>() {
                });
            }
            return classList;*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ResponseBody
    @RequestMapping("modules/{module}/{url}")
    public String module(@PathVariable("module") String module, @PathVariable("url") String url2, @RequestParam Map<String, Object> params) {
        try {
            //ProType proType= Class.forName("com.jiedeng.model.ProType").getInterfaces();
            String clientUrl = url + "/" + module + "/" + url2;
            if (!StringUtils.isEmpty(params)) {
                clientUrl += "?";
                clientUrl += getParam(params);

            }
            String ret = HttpClientHelper.doGet(clientUrl);
            return ret;
            ///原返回
            /*List<Map<String, Object>> classList = new ArrayList<Map<String, Object>>();
            if (ret != null) {
                classList = JSON.parseObject(ret.trim(), new TypeReference<List<Map<String, Object>>>() {
                });
            }
            return classList;*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String param;
    private int paramNum;

    public synchronized String getParam(Map<String, Object> params) {
        param = "";
        paramNum = 0;
        params.forEach((key, value) -> {
            if (paramNum > 0) {
                param += "&";
            }
            param += key + "=" + value;
            //System.out.println(key + ":" + value);

            paramNum++;
        });
        logger.info("参数-------" + param);
        return param;
    }
}